import type { TableColumnCtx } from 'element-plus';

import type { Dict } from '@croco/framework/types';

import type { DataFormItemProps, DataFormSchema } from '#/components/data-form/types';
import type { FieldProps, OnActionClickFn, RenderScope } from '#/components/data-table';

import { reactive } from 'vue';

import { useUserStore } from '@croco/framework/stores';

import { ElText } from 'element-plus';

export function useTable(enums: Record<string, Array<Dict> | undefined>, onActionClick: OnActionClickFn): FieldProps[] {
    const formatter = (row: any, column: TableColumnCtx) => {
        switch (column.property) {
            case 'createBy': {
                return row.createByUser?.nickname || row.createBy;
            }
            case 'modifyBy': {
                return row.modifyByUser?.nickname || row.modifyBy;
            }
            case 'status':
            case 'type': {
                const dict = enums[column.property]?.find((item) => item.value === row[column.property]);
                return h(ElText, { type: dict?.listClass || 'info' }, { default: () => dict?.label || '--' });
            }
        }
    };
    return [
        { prop: 'title', label: '标题', search: true, column: { minWidth: 300, showOverflowTooltip: true } },
        { prop: 'type', label: '类型', search: { value: '' }, column: { width: 90, align: 'center', formatter } },
        { prop: 'status', label: '状态', search: { value: '' }, column: { width: 90, align: 'center', formatter } },
        { prop: 'createBy', label: '创建者', column: { width: 190, formatter } },
        { prop: 'createTime', label: '创建时间', column: { width: 190 } },
        { prop: 'modifyBy', label: '修改者', column: { width: 190, formatter } },
        { prop: 'modifyTime', label: '修改时间', column: { width: 190 } },
        {
            column: {
                width: 150,
                render: [
                    { auth: 'system:config:edit', onClick: (scope: RenderScope) => onActionClick({ code: 'edit', scope }) },
                    { auth: 'system:config:remove', onClick: (scope: RenderScope) => onActionClick({ code: 'remove', scope }), type: 'danger' },
                ],
            },
        },
    ];
}

export function useForm(): DataFormSchema {
    const { username } = useUserStore();
    const rules = reactive({
        title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    });
    const fields: DataFormItemProps[] = [
        { prop: 'id', primary: true },
        { prop: 'title', label: '标题' },
        { prop: 'type', label: '类型', multiple: false, value: '1' },
        { prop: 'status', label: '状态', multiple: false, value: '0' },
        { prop: 'content', label: '内容' },
    ];
    return { rules, fields, username };
}
